const fs = require('fs')
const execSync = require('child_process').execSync;
const mongo_client = require('mongodb').MongoClient;
const obsTool = require('./obs');
const path = require('path')

const url = 'mongodb://localhost:27017';
const db_name = 'content_tags';

const db_operate = (cb) => {
    mongo_client.connect(url, (err, client) => {
        if (err) {
            console.log(err);
        }
        const db = client.db(db_name);
        cb(db);
    })
}

const find_img = (obj, cb) => {
    db_operate((db) => {
        const collection = db.collection('pic');
        collection.find({
            'tag1': obj.tag1,
            'tag2': obj.tag2,
            'tag3': obj.tag3
        }).toArray((err, result) => {
            console.log(result.length)
            if (err) {
                console.log(err);
                cb(err);
            } else {
                cb(result);
            }
        })
    })
}

class CompareTool {
    static prepare(tags, cb) {
        find_img(tags, (result) => {
            if (result.length != 0) {
                result.forEach(i => {
                    console.log(i['name']);
                    obsTool.download(i['name']);
                });
            }
            cb(result.length);
        });
    }

    static compare(objname, cb) {
        let ret
        const p = path.join(__dirname, '../');
        const output = execSync('python ./public/python/compare.py '
            + objname + " "
            + path.join(p, 'public/images'));

        if (output.toString() == '0') {
            console.log('The image you submit is qualified to register');
            ret = 0;
        }
        else {
            console.log('The image you submit is similar to a registered image');
            ret = 1;
        }



        cb(ret);
    }

    static clear() {
        var files = fs.readdirSync(path.join(__dirname, '../public/images'));
        files.forEach(element => {
            console.log(path.join(__dirname, '../public/images/') + element)
            fs.unlinkSync(path.join(__dirname, '../public/images/') + element);
        });
    }

    static insert_img = (obj, cb) => {
        db_operate((db) => {
            const collection = db.collection('pic');

            collection.insertOne({
                name: obj.name,
                tag1: obj.tag.tag1,
                tag2: obj.tag.tag2,
                tag3: obj.tag.tag3
            }, (result) => {
                collection.find({
                    'name': obj.name
                }).toArray((err, result) => {
                    if (err) {
                        console.log(err);
                        cb(err);
                    } else {
                        cb(result[0]['_id']);
                    }
                })
            })
        })
    }
}

module.exports = CompareTool